<template>
  <div class="app-box">
    <!-- 表单 -->
    <div class="form-list">
      <el-form :model="query" :inline="true" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="query.username" placeholder="关键字" clearable prefix-icon="el-icon-user" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="昵 称">
          <el-input v-model="query.nickname" placeholder="关键字" clearable prefix-icon="el-icon-s-custom" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="电 话">
          <el-input v-model="query.phone" placeholder="11位电话号码" clearable prefix-icon="el-icon-phone" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="性 别">
          <el-select v-model="query.sex" placeholder="请选择" clearable prefix-icon="el-icon-open" @change="handleQuery">
            <el-option :label="'男'" :value="1" />
            <el-option :label="'女'" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间" clearable>
          <el-date-picker
            v-model="query.timeInterval"
            type="daterange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item style="margin-left: 25px">
          <el-button :loading="searchLoading" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button :loading="resetQueryLoading" icon="el-icon-refresh" size="mini" @click="resetQuery">刷新</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div style="padding: 8px 9px 34px;background: #e7e7e74d;border-radius: 5px">
      <div style="display: flex">
        <div style="width: 18.2%;background: #FFFFFF;">
          <DepartTree ref="departTree" @currentDepart="res => query.departmentIds = res" />
        </div>
        <div style="width: 81.3%;margin-left: .5%;background: #FFFFFF;">
          <div class="table-header">
            <el-row :gutter="10" style="position: relative;">
              <el-col class="btn-style" :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                >新 增
                </el-button>
              </el-col>
              <el-col class="btn-style" :span="1.5">
                <el-button
                  type="info"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="selectIds.length < 1"
                  @click="handleUpdateRows"
                >批量编辑
                </el-button>
              </el-col>
              <el-col class="btn-style" :span="1.5">
                <el-popconfirm
                  title="确认删除所选中的任务吗??"
                  confirm-button-text="是"
                  cancel-button-text="否"
                  icon-color="red"
                  @confirm="handleDeleteRows"
                >
                  <el-button
                    slot="reference"
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="selectIds.length < 1"
                  >批量删除
                  </el-button>
                </el-popconfirm>
              </el-col>
              <el-col class="btn-style" :span="1.5">
                <el-button
                  :loading="exportLoading"
                  type="success"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport('用户列表', 'xlsx')"
                >导 出
                </el-button>
              </el-col>
              <el-col style="position: absolute;right: 0;" class="btn-style" :span="1.5">
                <el-input
                  v-model="search"
                  size="mini"
                  placeholder="输入用户名关键字搜索"
                />
              </el-col>
            </el-row>
          </div>
          <el-divider />
          <div style="overflow-x: auto;">
            <el-table
              v-loading="loading"
              :data="tableData"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgb(145 144 144 / 21%);"
              highlight-current-row
              @selection-change="handleSelectionChange"
            >
              <el-table-column align="center" type="selection" width="55" />
              <el-table-column align="center" prop="id" label="ID" :show-overflow-tooltip="true" />
              <el-table-column align="center" prop="departmentId" label="部 门" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  {{ departMap.get(scope.row.departmentId) }}
                </template>
              </el-table-column>
              <el-table-column align="center" prop="cover" label="头 像" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <el-image :src="scope.row.cover" style="width: 50%; height: 50%;" />
                </template>
              </el-table-column>
              <el-table-column align="center" prop="username" label="用户名" :show-overflow-tooltip="true" />
              <el-table-column align="center" prop="nickname" label="昵 称" :show-overflow-tooltip="true" />
              <el-table-column align="center" prop="sex" label="性 别" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  {{ scope.row.sex === 1 ? '男' : (scope.row.sex === 0 ? '女' : '未知') }}
                </template>
              </el-table-column>
              <el-table-column align="center" prop="birth" label="出生年月" :show-overflow-tooltip="true" />
              <el-table-column align="center" prop="phone" label="电 话" :show-overflow-tooltip="true" />
              <el-table-column align="center" prop="email" label="邮 箱" :show-overflow-tooltip="true" />
              <el-table-column align="center" prop="status" label="状 态" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  {{ scope.row.status === 1 ? '正常' : (scope.row.status === 0 ? '禁用' : '未知') }}
                </template>
              </el-table-column>
              <el-table-column align="center" prop="updateTime" label="更新时间" :show-overflow-tooltip="true" />
              <el-table-column align="center" prop="updateUserId" label="更新人" :show-overflow-tooltip="true" />
              <el-table-column align="center" prop="createdTime" label="注册时间" :show-overflow-tooltip="true" />
              <el-table-column align="center" fixed="right" label="操作" class-name="small-padding fixed-width">
                <template slot="header">
                  <span class="operate-1">操作</span>
                  <el-button class="operate-2" type="text" icon="el-icon-sort" size="small" plain @click="operateSwitch">操作</el-button>
                </template>
                <template slot-scope="scope">
                  <span :style="pcStyle" class="pc-style">
                    <el-tooltip class="item" effect="dark" content="详情" placement="top-start">
                      <el-button
                        size="mini"
                        type="info"
                        icon="el-icon-document"
                        @click="handleDetails(scope.row)"
                      />
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
                      <el-button
                        size="mini"
                        type="primary"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                      />
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                      <el-popconfirm
                        title="确认要删除吗??"
                        confirm-button-text="是"
                        cancel-button-text="否"
                        icon-color="red"
                        @confirm="handleDeleteRow(scope.row)"
                      >
                        <el-button
                          slot="reference"
                          style="margin-left: 10px;"
                          size="mini"
                          type="danger"
                          icon="el-icon-delete"
                        />
                      </el-popconfirm>
                    </el-tooltip>
                  </span>
                  <span :style="mbStyle" class="mobile-style">
                    <el-popover
                      placement="bottom"
                      title=""
                      width="190"
                      trigger="click"
                    >
                      <el-button
                        style="margin: 2px 4px"
                        size="mini"
                        type="info"
                        icon="el-icon-document"
                        @click="handleDetails(scope.row)"
                      >详情
                      </el-button>
                      <el-button
                        style="margin: 2px 4px"
                        size="mini"
                        type="primary"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                      >编辑
                      </el-button>
                      <el-popconfirm
                        title="确认要删除吗??"
                        confirm-button-text="是"
                        cancel-button-text="否"
                        icon-color="red"
                        @confirm="handleDeleteRow(scope.row)"
                      >
                        <el-button
                          slot="reference"
                          style="margin: 2px 4px"
                          size="mini"
                          type="danger"
                          icon="el-icon-delete"
                        >删除
                        </el-button>
                      </el-popconfirm>
                      <el-button slot="reference" type="text" size="mini">操作</el-button>
                    </el-popover>
                  </span>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              v-show="page.total>0"
              :page-sizes="[10, 20, 30, 40]"
              :total="page.total"
              :page.sync="page.pageNum"
              :limit.sync="page.pageSize"
              @pagination="querySysUserPage"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 弹框组件 -->
    <AddAndUpdateDialog v-if="addAndUpdShow" :title="addAndUpdTitle" :data="addAndUpdData" @returnData="addAndUpdReturnData" />
    <DetailsDialog v-if="detailsShow" :title="'系统用户详情'" :data="detailsData" @returnData="detailsReturnData" />
  </div>
</template>

<script>
import AddAndUpdateDialog from './component/AddAndUpdateDialog'
import DetailsDialog from './component/DetailsDialog'
import userAPI from '@/api/system/userAPI'
import DepartTree from '@/components/department/departTree'
import { mapGetters } from 'vuex'

export default {
  name: 'User',
  components: { DepartTree, DetailsDialog, AddAndUpdateDialog },
  computed: {
    ...mapGetters(['departMap'])
  },
  data() {
    return {
      query: {
        username: null,
        nickname: null,
        phone: null,
        sex: null,
        departmentIds: [],
        timeInterval: []
      },
      pcToMb: false,
      pcStyle: {},
      mbStyle: {},
      tableData: [],
      tableDataCache: [],
      search: '',
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      // 多选
      selectIds: [],
      selection: [],
      // 表头
      showSearch: true,
      // 表格加载
      loading: false,
      // 操作类型
      operateType: '',
      // 新增/编辑弹框
      addAndUpdShow: false,
      addAndUpdTitle: '',
      addAndUpdData: [],
      // 详情弹框
      detailsShow: false,
      detailsData: {},
      // 导出按钮加载
      exportLoading: false,
      // 搜索按钮加载
      searchLoading: false,
      // 重置按钮加载
      resetQueryLoading: false
    }
  },
  watch: {
    '$route': {
      immediate: true,
      handler: function(to, from) {
        // 拿到目标参数 to.query.id 去再次请求数据接口
        this.data = to.query.data
      }
    },
    search(val) {
      this.tableData = this.tableDataCache.filter(data => !val || data.username.toLowerCase().includes(val.toLowerCase()))
    }
  },
  created() {
    this.data = this.$route.query.data
    this.refreshData()
  },
  methods: {
    /** 移动端行操作按钮类型切换 */
    operateSwitch: function() {
      this.pcToMb = !this.pcToMb
      if (this.pcToMb) {
        this.pcStyle = {
          display: 'none'
        }
        this.mbStyle = {
          display: 'block'
        }
      } else {
        this.pcStyle = {
          display: 'block'
        }
        this.mbStyle = {
          display: 'none'
        }
      }
    },

    /** 重置查询 */
    resetQuery: function() {
      this.resetQueryLoading = true
      this.page = {
        pageNum: 1,
        pageSize: 10
      }
      this.query = {
        username: null,
        nickname: null,
        phone: null,
        sex: null,
        departmentIds: [],
        timeInterval: []
      }
      this.$refs.departTree.clearNodeSelected()
      this.refreshData()
    },

    /** 重置设置 */
    reSetting: function() {
      this.operateType = ''
    },

    /** 刷新数据 */
    refreshData: function() {
      this.querySysUserPage()
    },

    /** 搜索 */
    handleQuery: function() {
      this.searchLoading = true
      this.querySysUserPage()
    },

    /** 新增操作 */
    handleAdd: function() {
      this.operateType = 'Add'
      this.addAndUpdTitle = '新增系统用户'
      this.addAndUpdData = [{}]
      this.addAndUpdShow = true
    },
    /** 选中 */
    handleSelectionChange: function(selection) {
      this.selection = selection
      this.selectIds = selection.map(item => item.id)
    },
    /** 批量编辑 */
    handleUpdateRows: function() {
      this.operateType = 'UpdRows'
      this.addAndUpdTitle = '批量编辑系统用户'
      this.addAndUpdData = JSON.parse(JSON.stringify(this.selection))
      this.addAndUpdShow = true
    },

    /** 编辑行 */
    handleUpdate: function(row) {
      this.operateType = 'UpdRow'
      this.addAndUpdTitle = '编辑系统用户'
      this.addAndUpdData = [JSON.parse(JSON.stringify(row))]
      this.addAndUpdShow = true
    },

    /** 批量删除 */
    handleDeleteRows: function() {
      this.removeSysUserByIds(this.selectIds)
    },

    /** 删除行 */
    handleDeleteRow: function(row) {
      this.removeSysUserById(row.id)
    },

    /** 导出 */
    handleExport: function(fileName, suffix) {
      this.exportLoading = true
      userAPI.exportSysUserExcel(this.query).then(blob => {
        console.log(blob)
        const url = window.URL.createObjectURL(new Blob([blob]))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', `${fileName}.${suffix}`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        this.exportLoading = false
      })
    },

    /** 查看详情 */
    handleDetails: function(row) {
      this.detailsData = row
      this.detailsShow = true
    },

    /** 新增/编辑弹框返回数据 */
    addAndUpdReturnData: function(res) {
      this.addAndUpdShow = res.show
      if (res['data'] && res.data != null) {
        const rowList = res.data
        if (this.operateType === 'Add') {
          this.createSysUser(rowList[0])
        }
        if (this.operateType === 'UpdRows') {
          this.updateSysUserByList(rowList)
        }
        if (this.operateType === 'UpdRow') {
          this.updateSysUser(rowList[0])
        }
      }
    },

    /** 详情弹框返回数据 */
    detailsReturnData: function(res) {
      this.detailsShow = res.show
      if (res['data'] && res.data != null) {
        // const data = res.data
      }
    },
    // ----------------Api-------------------------------------------------------------
    /** 查询用户列表 */
    querySysUserPage: function() {
      this.loading = true
      const params = {
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
        username: this.query.username,
        nickname: this.query.nickname,
        phone: this.query.phone,
        sex: this.query.sex,
        departmentIds: JSON.stringify(this.query.departmentIds).replace(/]|[[]/g, ''),
        timeInterval: JSON.stringify(this.query.timeInterval).replace(/]|[[]/g, '')
      }
      userAPI.querySysUserPage(params).then(res => {
        this.tableDataCache = this.tableData = res.data.records
        this.page.total = res.data.total
        this.loading = false
        this.searchLoading = false
        this.resetQueryLoading = false
      })
    },

    /** 新增用户 */
    createSysUser: function(model) {
      userAPI.createSysUser(model).then(res => {
        this.$message({
          showClose: true,
          message: res.data,
          type: res.statusCode === 200 ? 'success' : 'error'
        })
        this.refreshData()
      })
    },

    /** 批量编辑 */
    updateSysUserByList: function(modelList) {
      userAPI.updateSysUserByList(modelList).then(res => {
        this.$message({
          showClose: true,
          message: res.data,
          type: res.statusCode === 200 ? 'success' : 'error'
        })
        this.refreshData()
      })
    },

    /** 编辑单条记录 */
    updateSysUser: function(model) {
      userAPI.updateSysUser(model).then(res => {
        this.$message({
          showClose: true,
          message: res.data,
          type: res.statusCode === 200 ? 'success' : 'error'
        })
        this.refreshData()
      })
    },

    /** 批量删除 */
    removeSysUserByIds: function(ids) {
      userAPI.removeSysUserByIds(ids).then(res => {
        this.$message({
          showClose: true,
          message: res.data,
          type: res.statusCode === 200 ? 'success' : 'error'
        })
        this.refreshData()
      })
    },

    /** 删除单条记录 */
    removeSysUserById: function(id) {
      userAPI.removeSysUserById(id).then(res => {
        this.$message({
          showClose: true,
          message: res.data,
          type: res.statusCode === 200 ? 'success' : 'error'
        })
        this.refreshData()
      })
    }
  }
}
</script>

<style scoped>
/* 边框盒子 */
.app-box {
  margin: 1% 1%;
}

/* 搜索表单 */
.form-list {
  border-radius: 5px;
  margin-bottom: 10px;
  padding-top: 24px;
  background: #e9eeef21;
  box-shadow: 2px 2px 6px 0px #8b83835e;
}

/* 数据表格 */
.table-list {
  border-radius: 5px;
  margin-bottom: 10px;
  padding: 16px 6px 1px;
  background: #e9eeef21;
  box-shadow: 2px 2px 6px 0px #8b83835e;
}

/* 表格内操作按钮 */
.mobile-style {
  display: none;
}
/* 表头按钮 */
.table-header {
  margin: 5px 5px 0;
}
/* 移动端行内操作按钮类型展示 */
.operate-1 {
  display: none;
}
/* 样式穿透 */
/deep/ .el-divider--horizontal {
  margin: 5px 0;
}
/deep/ .el-col-24 {
  /*width: 21%;*/
}
/deep/ .el-col-2 {
  text-align: center;
}
/deep/ .el-date-editor> input {
  /*width: 346px;*/
}
/deep/ .pagination-container .el-pagination {
  right: 0;
  position: absolute;
  margin: -18px 0px;
}
/deep/ .pagination-container {
  position: relative;
  height: 25px;
  padding: 0px;
  margin-top: 9px;
  border-radius: 0 0 5px 0;
  /*padding: -1px 20px !important;*/
}
/deep/ .el-table .fixed-width .el-button--mini {
  text-align: center;
  width: inherit;
  padding: 5px 5px;
  border-radius: 12px;
}

/* 移动端自适应 */
@media screen and (max-width: 1056px) {
  /deep/ .el-col-6 {
    width: 99%;
  }
  .pc-style {
    display: none;
  }
  .table-header .btn-style {
    margin: 2px;
  }
  .mobile-style {
    display: block;
  }
  .operate-1 {
    display: block;
  }
  .operate-2 {
    display: none;
  }
}
</style>
